from http.server import BaseHTTPRequestHandler, HTTPServer
import time


# 自定义请求处理类
class HelloWorldHandler(BaseHTTPRequestHandler):
    # 处理GET请求
    def do_GET(self):
        # 只处理根路径请求
        if self.path == '/':
            # 发送200响应码
            self.send_response(200)
            # 设置响应头
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            # 响应内容
            message = "Hello World!"
            # 将内容编码为字节流并发送
            self.wfile.write(bytes(message, "utf8"))
        else:
            # 对于其他路径返回404
            self.send_response(404)
            self.end_headers()
            self.wfile.write(bytes("404 Not Found", "utf8"))


# 主函数
def run(server_class=HTTPServer, handler_class=HelloWorldHandler, port=8000):
    # 服务器地址
    server_address = ('', port)
    # 创建服务器实例
    httpd = server_class(server_address, handler_class)
    # 获取当前时间
    start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

    print(f"服务器启动于 {start_time}")
    print(f"访问地址: http://localhost:{port}")
    print("按 Ctrl+C 停止服务器")

    try:
        # 启动服务器
        httpd.serve_forever()
    except KeyboardInterrupt:
        # 处理Ctrl+C中断
        pass

    # 关闭服务器
    httpd.server_close()
    end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    print(f"\n服务器于 {end_time} 停止")


# 运行服务器
if __name__ == "__main__":
    run()